package com.eportal.action.background;

import com.eportal.action.BaseAction;
import com.eportal.domain.*;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.*;
import com.eportal.util.*;
import com.framework.jqgrid.JqGridPager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 硬件管理
 * @author chencheng
 *
 */
public class TLocksAction extends BaseAction implements ModelDriven<TLock> {

	private static MdExpiringMap<String, HSSFWorkbook> fileMap = new MdExpiringMap<String, HSSFWorkbook>(240, 10);
    /**
	 * @author chenchengo
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TLocksAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    private TLocksService tlocksService;
    @Autowired
    private AppStoreService appStoreService;
    @Autowired
    private TAgentService tAgentService;
    @Autowired
    private SysOptService sysOptService;
    @Autowired
    private TKeysService tKeysService;
    @Autowired
    private TUsersService tUsersService;
	/**
     * 硬件管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
        return SUCCESS;
    }

    /**
     * 锁厂硬件管理
     */
    public String listView2() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("rLevel", user.getrLevel());
    	return SUCCESS;
    }

    /**
     * 导出设备数据的页面
     * by wangk
     * @return
     */
    public String exportIndex() {
    	return SUCCESS;
    }

    /**
     * 生成数据excel
     * by wangk
     * @return
     */
    public String export() {
    	Map map = new HashMap();
    	try{
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
			String[] titles = {"pid","激活码","二维码内容","二维码图片"};
			String spid = getRequest().getParameter("pidBegin");
			String epid = getRequest().getParameter("pidEnd");
			if(spid==null||spid.length()<1){
				map.put("code", "-1");
				map.put("msg", "pid必填");
				responseBody(map);
				return null;
			}
			if(epid==null||epid.length()<1){
				map.put("code", "-1");
				map.put("msg", "pid必填");
				responseBody(map);
				return null;
			}
			spid = spid.replaceAll(" ", "");
			epid = epid.replaceAll(" ", "");
			StringBuilder where = new StringBuilder(" and (pid>='"+spid+"' and pid<='"+epid+"')");
			int userRole =  (Integer) getSession().getAttribute("userRole");
			if(userRole==3||userRole==4){//合作级管理员，只能取自己的数据
				where.append(" and agtcode='"+user.getAgtCode()+"'");
			}else if(userRole==1||userRole==2){//平台管理员可以取全部

			}else{//其他管理员，暂时不能取到数据
				where.append(" and 1=2");
			}
			List<TLock> list =tlocksService.getBySql(where.toString());
			String fileid = UUID.randomUUID().toString();
			//fileMap.put(fileid, ExcelUtil.export("硬件数据", dataList));//考虑到激活码等敏感信息，将文件放在内存中，长时间没下载，或者下载一次后清除。


			final int qrcodeWidth=280;//二维码的宽度
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet1 = wb.createSheet("device");
			sheet1.setColumnWidth(3, Double.valueOf(qrcodeWidth*35.7).intValue());//宽度 n像素
            sheet1.setColumnWidth(2, Double.valueOf(300*35.7).intValue());
            sheet1.setColumnWidth(1, Double.valueOf(200*35.7).intValue());
            sheet1.setColumnWidth(0, Double.valueOf(200*35.7).intValue());
            HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
        	Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//编码
    		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);//容错率
    		hints.put(EncodeHintType.MARGIN, 0);
            for(int i=0;i<list.size();i++){
				TLock lock = list.get(i);
				String url = WebUtil.getReqPreUrl(getRequest()) + "a?p=" + lock.getPid() + "&c=" + lock.getCheckCode()
						+ "&v=1";
				BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeWidth, hints);
				BufferedImage bufferImg = toBufferedImage(bitMatrix);
				ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
				ImageIO.write(bufferImg, "jpg", byteArrayOut);

            	//画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）

                //anchor主要用于设置图片的属性
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,(short) 3, i+1, (short) 4, i+2);
                //anchor.setAnchorType(3);
                //插入图片
                patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
                HSSFRow row1 = sheet1.createRow(i+1);
                row1.setHeight((short) (qrcodeWidth*15.625)); //高度 n像素
                row1.createCell(0).setCellValue(lock.getPid());
                row1.createCell(1).setCellValue(lock.getCheckCode());

                row1.createCell(2).setCellValue(url);
            }

            HSSFRow row1 = sheet1.createRow(0);
			for(int j=0;j<titles.length;j++){
				  row1.createCell(j).setCellValue(titles[j]);
			}
			fileMap.put(fileid, wb);

			map.put("code", "1");
			map.put("msg", "操作成功");
			map.put("url", getRequest().getContextPath()+"/admin/tlocks_getFile.action?id="+fileid);
			responseBody(map);
    	}catch(Exception e){
    		log.error(this, e);
    		map.put("code", "-1");
			map.put("msg", "导出数据繁忙");
    	}
    	return null;
    }

	private static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

    /**
     * 获取文件
     * @return
     */
    public String getFile() {
    	Map map = new HashMap();
    	try{

    		String id = getRequest().getParameter("id");
    		HSSFWorkbook workbook = fileMap.get(id);
    		if(workbook!=null){

    			getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String("device_"+DateUtils.formatDatetime(new Date(), "yyyy_MM_dd_HHmmss")+".xls"));
                //getResponse().setContentType("application/octet-stream");
    			getResponse().setContentType("multipart/form-data");
    			 workbook.write(getResponse().getOutputStream());
                getResponse().getOutputStream().flush();
                getResponse().getOutputStream().close();
                workbook=null;//清除文件
    		}
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	return null;
    }
    /**
     * 硬件列表
     */
    public void page() throws Exception {
        JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String areaCode = getRequest().getParameter("areaCode");
    	String pid = getRequest().getParameter("pid");
    	String cbName = getRequest().getParameter("cbName");
    	String status = getRequest().getParameter("status");
    	String type = getRequest().getParameter("type");
    	String pid1 = getRequest().getParameter("pid1");
    	String pid2 = getRequest().getParameter("pid2");
    	String checkstatus = getRequest().getParameter("checkstatus");

    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.type='");//类型：0：一般合作方硬件，1：锁厂硬件
		//主板厂商   在这里的考虑是主板厂商只能发给锁厂 所以将type值固定为1 而不是前台传来的 //todo Updated by Saber on 2017/7/26 下午4:27
		if(userRole == 7 ){
			where.append("1"); //todo Created by Saber on 2017/7/27 下午5:00
        }else {
			where.append(type); //todo Updated by Saber on 2017/7/27 下午5:00
        }
		where.append("' ");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (!StringUtils.isBlank(agtCode)) {
                where.append(" and t.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
        	if (!StringUtils.isBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
        	if (userRole == 21) {
    			where.append(" and a.sysoptId =");
    			where.append(user.getSid());
			}
		}else if (userRole == 3 || userRole == 4 || userRole == 7 ) { //todo Updated by Saber on 2017/7/25 下午5:16
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			if (!StringUtils.isBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}


    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(c.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	if (!StringUtils.isBlank(pid)) {
    		where.append(" and t.pid = '");
    		where.append(pid);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(cbName)) {
    		where.append(" and t.install_lock_name like '%");
    		where.append(cbName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(status)) {
    		where.append(" and t.status = '");
    		where.append(status);
    		where.append("'");
    	}
      	if (!StringUtils.isBlank(pid1)) {
    		where.append(" and t.pid >= '");
    		where.append(pid1);
    		where.append("'");
    	}
      	if (!StringUtils.isBlank(pid2)) {
    		where.append(" and t.pid <= '");
    		where.append(pid2);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(checkstatus)) {
    		where.append(" and t.checkstatus = '");
    		where.append(checkstatus);
    		where.append("'");
    	}
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        List<TLock> tLocks = tlocksService.list(page);
        jqGridQueryMap(TLock.class, getRequest(), tLocks, getResponse(), page);
    }
    /**
     * 硬件列表
     */
    public void pageApp() throws Exception {
    	String page = getRequest().getParameter("page");
    	String size = getRequest().getParameter("size");
    	if (StringUtils.isBlank(size) || StringUtils.isBlank(page)) {
			return;
		}
    	int pageNum = Integer.parseInt(page);
    	int sizeNum = Integer.parseInt(size);
    	int beginNum = pageNum * sizeNum;
    	int endNum = (pageNum+1) * sizeNum;
    	String where  = getPageAppWhere();

    	List<TLock> tLocks = tlocksService.listPageApp(where,beginNum,endNum);
    	responseBody(tLocks);
    }

    private String getPageAppWhere() {
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.type='1' ");
    	if (userRole == 3 || userRole == 4) {
    		where.append(" and t.agtCode ='");
    		where.append(user.getAgtCode());
    		where.append("'");
    	}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
		return where.toString();
	}

    /**
     * 生成设备转让的二维码
     * @return
     */
    public String createQrcode4Transfer(){
    	try{
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    		String sid = getRequest().getParameter("sid");
    		TLock lock = tlocksService.get(Long.valueOf(sid));
    		String code = getCode4Transfer(lock.getCheckCode());
    		if(user.getCommunityId().equals(lock.getCommunityId())){
    			String url = WebUtil.getReqPreUrl(getRequest())+"admin/tlocks_a.action?i="+sid+"&c="+code+"&u="+user.getSid();
    			getRequest().setAttribute("url", url);
    		}else{
    			log.error("设备不属于该用户,sid="+sid);
    			getRequest().setAttribute("msg", "钥匙信息不匹配，请重新尝试");
    			return "exception";
    		}

    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
    	return SUCCESS;
    }

    /**
     * 智能锁转移用户,二维码的链接，为减少二维码复杂度，用了‘a’
     * @return
     */
    public String a(){
    	try{
    		String sid = getRequest().getParameter("i");
    		String code = getRequest().getParameter("c");
    		String sysoptId = getRequest().getParameter("u");
    		getRequest().setAttribute("i", sid);
    		getRequest().setAttribute("c", code);
    		getRequest().setAttribute("u", sysoptId);
    		String userid = getRequest().getParameter("userid");
    		//userid="13";
    		if(userid==null){
    			getResponse().sendRedirect(Config.MD_OPEN_TSHELVES_URL+"/app/authWebLogin.do?url="+URLEncoder.encode(WebUtil.getReqPreUrl(getRequest())+"admin/tlocks_a.action?i="+sid+"&c="+code+"&u="+sysoptId));
    		}else{
    			getRequest().getSession().setAttribute("app_userid", userid);
    			TLock lock = tlocksService.get(Long.valueOf(sid));
        		lock.getCommunityId();
    			Sysopt opt = sysOptService.get(Long.valueOf(sysoptId));
    			if(opt.getCommunityId().equals(lock.getCommunityId())){
            		String code_ = getCode4Transfer(lock.getCheckCode());
            		if(code.equals(code_)){
            			String tel_ = opt.getTel().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
            			getRequest().setAttribute("tel_", tel_);
            			getRequest().setAttribute("tel",opt.getTel());
            			return SUCCESS;
            		}else{
            			getRequest().setAttribute("msg", "钥匙信息不匹配，请重新尝试");
            			return "exception";
            		}
    			}else{
    				log.error("设备不属于该用户,sid="+sid);
        			getRequest().setAttribute("msg", "钥匙信息不匹配，请重新尝试");
        			return "exception";
    			}
    		}

    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
    	return "exception";
    }

    /**
     * 检测转移设备所需的验证码及其他信息
     */
    public void checkTransferCode(){
    	Map map = new HashMap();
    	try{

    		String sid = getRequest().getParameter("i");
    		String code = getRequest().getParameter("c");
    		String telCode = getRequest().getParameter("telCode");
    		String sysoptId = getRequest().getParameter("u");
    		String appUserid = (String)getSession().getAttribute("app_userid");
			TLock lock = tlocksService.get(Long.valueOf(sid));
    		lock.getCommunityId();
			Sysopt opt = sysOptService.get(Long.valueOf(sysoptId));
			if(opt.getCommunityId().equals(lock.getCommunityId())){
        		String code_ = getCode4Transfer(lock.getCheckCode());
        		if(code.equals(code_)){
        			if(SmsHelper.checkSMSValidCache(opt.getTel(), telCode)){
        				Sysopt appOpt = sysOptService.getByAppUserid(appUserid);
        				if(appOpt==null){//之前没绑定的注册
        					map.put("code", "1");
        	    			map.put("login_status", "1");

        				}else{//已绑定的新增
        					sysOptService.loginBySysopt(appOpt);//设置sessiom等信息
        					map.put("code", "1");
        					map.put("login_status", "2");
        				}
        				map.put("pid", lock.getPid());
    	    			map.put("checkcode",lock.getCheckCode());
    	    			getSession().setAttribute("transferPid", lock.getPid());
        			}else{
        				map.put("code", "0");
            			map.put("msg", "验证码不正确");
        			}
        		}else{
        			map.put("code", "0");
        			map.put("msg", "钥匙信息不匹配，请重新尝试");
        		}
			}else{
    			map.put("code", "0");
    			map.put("msg", "钥匙所属不匹配，请重新尝试");
    		}

    	}catch(Exception e){
    		log.error(this, e);
    		map.put("code", "0");
			map.put("msg", "服务器繁忙，请稍后再试");
    	}
    	responseBody(map);
    }
    /**
     * 将checkcode md5后 取前n位
     * @param checkcode
     * @return
     */
    private String getCode4Transfer(String checkcode){
    	String str = MD5.MD5Encode(checkcode);
    	String code = str.substring(0, 7);
    	return code;
    }

	/**
     * 硬件增加
     */
    public String addView() {
        return SUCCESS;
    }

    /**
     * 硬件新增保存
     */
    public void add(){

    	result = new HashMap<String, Object>();
    	String type = getRequest().getParameter("type");
    	try{
    		TLock tLock = getModel();


        	if("2".equals(type)){
    			String transferPid = (String)getSession().getAttribute("transferPid");
    			if(!tLock.getPid().equals(transferPid)){
    				result.put("code", 0);
        			result.put("msg", "输入的pid和需要转移的pid不一致，请检查信息或重新尝试");
        			responseBody(result);
        			return;
    			}
    		}

        	if(StringUtils.isBlank(tLock.getPid())){
        		 result.put("code", 0);
                 result.put("msg", "pid不能为空，请输入");
                 responseBody(result);
                 return;
        	}
        	if(StringUtils.isBlank(tLock.getCheckCode())){
        		result.put("code", 0);
                result.put("msg", "校验码不能为空，请输入");
                responseBody(result);
                return;
        	}
            Sysopt user= (Sysopt)getSession().getAttribute("user");
        	result = tlocksService.addMethod(tLock,type,user);

        	try{
        		//智能锁app用户新增设备时，自动为其添加一把钥匙
        		if("1".equals(result.get("code"))){
        			String userid = (String)getRequest().getSession().getAttribute("app_userid");
            		if(userid!=null){
            			TUsers tuser = tUsersService.getByUserid(userid);
            			if(tuser!=null){
            				TLock lock  = tlocksService.getByPid(tLock.getPid());
            				if(lock!=null){
            					List list = new ArrayList();
            					list.add(lock);
            					tKeysService.SyncTo(tuser, list, DateUtils.formatDate(DateUtils.addYear(new Date(), 20)), tLock.getAgtCode(), new Date());//分配一把20年的钥匙给用户
            				}
            			}
            		}
        		}
			}catch(Exception e){
				log.error(this,e);
			}
    	}catch(Exception e){
    		log.error(this, e);
    		 result.put("code", 0);
             result.put("msg", "添加失败");
    	}


        responseBody(result);
    }

    /**
     * APP端——添加智能锁
     */
    public String addLockApp() {
    	String type = getRequest().getParameter("type");
    	if(type==null){
    		type="1";//默认为正常的注册，type=2是硬件转移注册
    	}
    	getRequest().setAttribute("pid", getRequest().getParameter("pid"));
    	getRequest().setAttribute("checkcode", getRequest().getParameter("checkcode"));
    	getRequest().setAttribute("type", getRequest().getParameter("type"));
    	return SUCCESS;
    }

    /**
     * APP端——智能锁管理
     */
    public String lockManagerApp() {
    	try{
    		//TODO wangk 2017-8-9 09:38:38 智能锁2.0改版，跳转地址有变化
    		/*int countSize = tlocksService.countSizeApp(getPageAppWhere());
        	if(countSize==0){//设备数量为0时，跳转到添加
        		addLockApp();
        		return "addLockApp";
        	}*/
    		int countSize = tlocksService.countSizeApp(getPageAppWhere());
        	if(countSize==0){//设备数量为0时，跳转到添加
        		addLockApp();
        		return "addLockApp";
        	}else{
        		getResponse().setStatus(301);
    			getResponse().sendRedirect(Config.MD_OPEN_TSHELVES_URL+"/lifes/lock/lock_grammer.do");
        	}
    		
			return null;
    	}catch(Exception e){
    		log.error(this, e);
    	}

    	return SUCCESS;
    }

    /**
     * APP端——智能锁详情列表
     */
    public String listViewApp() {
    	int countSize = tlocksService.countSizeApp(getPageAppWhere());
    	if (countSize != 0) {
    		countSize = countSize/10 +1;
		}
    	getRequest().setAttribute("countSize",countSize);
    	return SUCCESS;
    }


    /**
     * 硬件修改
     */
    public String editInstallView() {
    	Map<String, String> map = tlocksService.getInstallTlock(getModel().getSid());
        getRequest().setAttribute("map", map);
        return SUCCESS;
    }

    /**
     * 智能门禁安装
     */
    public String installTlock() {
        return SUCCESS;
    }
    /**
     * 硬件更换，在硬件损坏等情况下，社区可以更换设备
     */
    public String change() {
    	Sysopt sysopt = (Sysopt)getRequest().getSession().getAttribute("user");
    	Map<String, String> map = tlocksService.getInstallTlock(getModel().getSid());
        getRequest().setAttribute("map", map);
        List list = tlocksService.getBySql(" and communityId='"+sysopt.getCommunityId()+"' and STATUS='0'");//本社区下，为安装的设备，才能作为可被替换的设备
        getRequest().setAttribute("list", list);
        return SUCCESS;
    }


    /**
     * 保存硬件更新
     */
    public void saveChange() {

		try {
			Sysopt sysopt = (Sysopt) getRequest().getSession().getAttribute("user");
			String sid = getRequest().getParameter("sid");
			String newPid = getRequest().getParameter("newPid");
			String checkcode = getRequest().getParameter("checkcode");
			TLock lock = tlocksService.getByPid(newPid);
			if(lock!=null){
				if("1".equals(lock.getStatus())){
					result.put("code", 0);
					result.put("msg", "设备已被安装，请重新确认信息");
					responseBody(result);
					return;
				}
				if(!checkcode.equals(lock.getCheckCode())){
					result.put("code", 0);
					result.put("msg", "激活码不正确");
					responseBody(result);
					return;
				}
			}else{
				result.put("code", 0);
				result.put("msg", "没有匹配的硬件");
				responseBody(result);
				return;
			}

			Map map = tlocksService.changeTlockAgt(newPid, sysopt.getAgtCode());// 执行发货操作
			if((Integer)map.get("code")==1){
				tKeysService.change(sid, lock.getSid().toString(), sysopt.getCommunityId(),sysopt.getSid(),sysopt);
				result.put("code", 1);
				result.put("msg", "操作成功");
			}else{
				result.put("code", 0);
	  	        result.put("msg", "操作失败");
			}

		}catch(MdKnownRunTimeException e){
    		result.put("code", 0);
  	        result.put("msg", e.getMessage());
  	      log.error(this, e);
    	}catch (Exception e) {
    		log.error(this, e);
    		result.put("code", 0);
  	        result.put("msg", "操作失败");
		}

    	responseBody(result);
    }

    /**
     * 硬件修改保存
     */
    public void update(){
    	String sid= getRequest().getParameter("sid");
    	String type= getRequest().getParameter("type");
    	String building= getRequest().getParameter("building");
    	String unit= getRequest().getParameter("unit");
    	String beforeunit = getRequest().getParameter("beforeunit");
    	String name = getRequest().getParameter("installLockName");
    	try {
            Sysopt user = (Sysopt)getRequest().getSession().getAttribute("user");
    		result = tlocksService.updateMethod(sid,type,building,unit,name,beforeunit,user);
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
  	      log.error(this, e);
		}catch (Exception e) {
			log.error(this, e);
			result.put("code", 0);
  	        result.put("msg", "修改硬件安装点失败");
  	      log.error(this, e);
		}
    	responseBody(result);
    }

    /**
     * 获取设备激活信息
     */
    public void getActiveInfo(){
    	String mac= getRequest().getParameter("mac");
    	String device_name= getRequest().getParameter("device_name");
    	String appid= getRequest().getParameter("appid");
    	try {
    		AppStore appStore = (AppStore)appStoreService.get("from AppStore where appid='"+appid+"'");
    		mac= mac.replace(" ", "");
        	device_name= device_name.replace(" ", "");
        	mac = mac.toUpperCase();
        	String[] macArr = mac.split(",");
        	String[] nameArr = device_name.split(",");
        	List dataList =new ArrayList();
        	for(int i=0;i<macArr.length;i++){
        		String mac_ = macArr[i];
        		if(mac_!=null&&mac_.length()>0){
        			String device_name_ = nameArr[i];
        			List<TLock> list = tlocksService.getBySql(" and mac20='"+mac_+"' and ssid1='"+device_name_+"' and agtcode='"+appStore.getAgtCode()+"' and status='2'");
                	log.info("select * from t05_locks  where mac20='"+mac_+"' and ssid1='"+device_name_+"' and agtcode='"+appStore.getAgtCode()+"' and status='2'");
                	Map dataMap = new HashMap();

                	if(list.size()==0){
                		dataMap.put("bizerr", "-1");//没有设备
                	}else if(list.size()>1){
                		dataMap.put("bizerr", "-2");//设备不知一个
                	}else{
                		TLock bean = list.get(0);
                		result.put("code", "1");
              	        result.put("msg", "ok");
              	        dataMap.put("pid",bean.getPid());
        	      	    dataMap.put("bizerr","1");
        	      	    dataMap.put("checkcode",bean.getCheckCode());
                	}
                	dataList.add(dataMap);
        		}
        	}

        	result.put("code", "1");
  	        result.put("msg", "ok");
        	result.put("data", dataList);
        	log.info("============"+JSONObject.fromObject(result).toString());
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
  	      log.error(this, e);
		}catch (Exception e) {
			log.error(this, e);
			result.put("code", 0);
  	        result.put("msg", "获取设备信息失败");
  	      log.error(this, e);
		}

    	responseBody(result);
    }


    /**
     * 删除
     */
    public void delete(){
    	String param_ids = getRequest().getParameter("ids");
    	result = tlocksService.deleteMethod(param_ids);
        responseBody(result);
    }

    /**
     * 硬件发货页面
     */
    public String sendTlocksView() {
        return SUCCESS;
    }

    /**
     * 可发货硬件数据
     * @throws Exception
     */
    public void notSendList() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	String pid1 = getRequest().getParameter("pid1");
    	String pid2 = getRequest().getParameter("pid2");
    	StringBuilder where = new StringBuilder(" 1=1 ");

    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");

    	if (userRole == 1 || userRole == 2) {
                where.append(" and agtcode is null ");
		}else	if (userRole == 3 || userRole == 4 || userRole == 7 ) { //todo Updated by Saber on 2017/7/25 下午5:18
			where.append(" and agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
		}else if (userRole == 5 || userRole == 6) {

		}else{
			return;
		}

//    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
//		where.append(" and communityId ='");
//		where.append(user.getCommunityId());
//		where.append("'");
    	where.append(" and status ='-1'");
    	if (StringUtils.isNotBlank(pid1)) {
            where.append(" and pid >= '");
            where.append(pid1);
            where.append("'");
//            where.append(" and pid like '%");
//            where.append(pid1.substring(0, 5));
//            where.append("%'");
        }
    	if (StringUtils.isNotBlank(pid2)) {
            where.append(" and pid <= '");
            where.append(pid2);
            where.append("'");
//            if (StringUtils.isBlank(pid2)) {
//            	where.append(" and pid like '%");
//            	where.append(pid2.substring(0, 5));
//            	where.append("%'");
//			}
        }
    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<TLock> tLocks = tlocksService.listTLocks(jqGridPager);
        jqGridQueryMap(TLock.class, getRequest(), tLocks, getResponse(), jqGridPager);
    }

    /**
     * 硬件发货选择合作方页面
     */
    public String sendSelectTagent() {
    	String pids = getRequest().getParameter("pids");
    	getRequest().setAttribute("pids", pids);

    	return SUCCESS;
    }

    /**
     * 硬件批量发货页面，根据pid初始值和默认值发货
     */
    public String sendBatchTagent() {
    	return SUCCESS;
    }

    /**
     * 选择合作方发货
     */
    public void sendToTagent(){
    	String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String pids = getRequest().getParameter("pids");
    	if(StringUtils.isBlank(agtCode) && StringUtils.isBlank(communityId)  ){
    		result.put("code", 0);
  	        result.put("msg", "请选择要发货的公司或者社区");
  	        responseBody(result);
  	        return;
    	}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        int userRole =  (Integer) getSession().getAttribute("userRole");    //todo Created by Saber on 2017/7/27 上午11:34
        if (StringUtils.isBlank(agtCode)) {
    		agtCode = user.getAgtCode();
		}
    	StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
    	where.append(" and agtCode ='");
    	where.append(agtCode);
    	where.append("'");
    	List<AppStore> appStores = appStoreService.list(where.toString());
    	if(appStores.size()<1){
    		result.put("code", "-1");
			result.put("msg", "该未合作方还未指定APP,请添加应用");
			responseBody(result);
			return;
    	}
    	try {
			result = tlocksService.sendToTagentMethod(agtCode,communityId,pids,user,userRole);//todo Updated by Saber on 2017/7/27 上午11:33
        } catch (Exception e) {
			result.put("code", "-1");
			result.put("msg", "操作失败");
			log.error(this, e);
		}
        responseBody(result);
    }

    /**
     * 硬件批量发货，根据pid初始值和默认值发货
     */
    public void sendToBatchTagent(){
    	String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String pidBegin = getRequest().getParameter("pidBegin");
    	String pidEnd = getRequest().getParameter("pidEnd");
    	if(StringUtils.isBlank(agtCode) && StringUtils.isBlank(communityId)  ){
    		result.put("code", 0);
    		result.put("msg", "请选择要发货的公司或者社区");
    		responseBody(result);
    		return;
    	}
    	if (StringUtils.isBlank(pidBegin) || StringUtils.isBlank(pidEnd) ) {
    		result.put("code", 0);
    		result.put("msg", "请输入pid初始值和默认值");
    		responseBody(result);
    		return;
		}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        int userRole =  (Integer) getSession().getAttribute("userRole"); //todo Created by Saber on 2017/7/27 上午11:38
        if (StringUtils.isBlank(agtCode)) {
    		agtCode = user.getAgtCode();
		}
    	StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
    	where.append(" and agtCode ='");
    	where.append(agtCode);
    	where.append("'");
    	List<AppStore> appStores = appStoreService.list(where.toString());
    	if(appStores.size()<1){
    		result.put("code", "-1");
    		result.put("msg", "该未合作方还未指定APP,请添加应用");
    	}
    	try {

    		result = tlocksService.sendToBatchTagentMethod(agtCode,communityId,pidBegin,pidEnd,user,userRole); //todo Updated by Saber on 2017/7/27 上午11:37
        } catch (Exception e) {
    		result.put("code", "-1");
    		result.put("msg", "操作失败");
    		log.error(this, e);
    	}
    	responseBody(result);
    }

    /**
     * 已发货硬件记录页面
     */
    public String haveSendListView() {
        return SUCCESS;
    }

    /**
     * 发货记录
     * @throws Exception
     */
    public void haveSendList() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");

    	StringBuilder where = new StringBuilder(" 1=1 ");
    	String operationContent = getRequest().getParameter("operationContent");
    	String operator = getRequest().getParameter("operator");
    	String sendTime = getRequest().getParameter("sendTime");

    	if (!StringUtils.isBlank(operationContent)) {
    		where.append(" and t.comm like '%");
    		where.append(operationContent);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(operator)) {
    		where.append(" and t.cUserName = '");
    		where.append(operator);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(sendTime)) {
//    		where.append(" and  >= to_date( '");
    		where.append(" and  TO_CHAR (t.cTime,'YYYY-MM-DD') ='");
    		where.append(sendTime);
    		where.append("'");
    	}
    	if (userRole == 1 || userRole == 2) {
            where.append(" and t.type =0");
		}else if (userRole == 21) {
            where.append(" and a.sysoptId =");
            where.append(user.getSid());
		}else if (userRole == 3 || userRole == 4) {
			where.append(" and t.type =1");
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("' ");
		}else if (userRole == 5 || userRole == 6) {
			return;
		}else if(userRole == 7 ){ //todo Updated by Saber on 2017/7/26 上午10:33
//			where.append(" and t.type =0");
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("' ");
		}
    	where.append(" and dType ='0'");

    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<LocksDeliveryLog> locksDeliveryLogs = tlocksService.listLocksDeliveryLog(jqGridPager);
        if (locksDeliveryLogs==null) {
        	jqGridQueryMap(TLock.class, getRequest(), locksDeliveryLogs, getResponse(), jqGridPager);
        	return;
        }
        jqGridQueryMap(TLock.class, getRequest(), locksDeliveryLogs, getResponse(), jqGridPager);
    }


    /**
     * 安装页面
     */
    public String installTlocksView() {
        return SUCCESS;
    }

    /**
     * 未安装列表
     * @throws Exception
     */
    public void installTlocksList() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
		where.append(" and communityId ='");
		where.append(user.getCommunityId());
		where.append("'");
		where.append(" and status ='0'");
    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<TLock> tLocks = tlocksService.listTLocks(jqGridPager);
        jqGridQueryMap(TLock.class, getRequest(), tLocks, getResponse(), jqGridPager);
    }

    /**
     * 硬件安装
     */
    public void installTlocks() {
    	String id= getRequest().getParameter("id");
    	String type= getRequest().getParameter("type");
    	String building= getRequest().getParameter("building");
    	String unit= getRequest().getParameter("unit");
    	String name= getRequest().getParameter("name");

        try {
            Sysopt user = (Sysopt) getSession().getAttribute("user");   //todo Created by Saber on 2017/7/27 上午11:01
    		result = tlocksService.installTlocksMethod(id,type,building,unit,name,user); //todo Updated by Saber on 2017/7/27 上午11:01
        } catch (MdKnownRunTimeException e) {
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
		}catch (Exception e) {
			result.put("code", 0);
  	        result.put("msg", "安装硬件失败");
  	      log.error(this, e);
		}
        responseBody(result);

    }

    /**
     * 硬件安装
     */
	public void installTlocks2() {
		String id = getRequest().getParameter("pid");
		String checkcode = getRequest().getParameter("checkcode");
		String type = getRequest().getParameter("type");
		String building = getRequest().getParameter("cBuildingId");
		String unit = getRequest().getParameter("unitId");
		String name = getRequest().getParameter("lockname");
		try {
			TLock lock = tlocksService.getByPid(id);
			if(lock!=null){
				if("1".equals(lock.getStatus())){
					result.put("code", 0);
					result.put("msg", "设备已被安装，请重新确认信息");
					responseBody(result);
					return;
				}
				if(!checkcode.equals(lock.getCheckCode())){
					result.put("code", 0);
					result.put("msg", "激活码不正确");
					responseBody(result);
					return;
				}
			}else{
				result.put("code", 0);
				result.put("msg", "没有匹配的硬件");
				responseBody(result);
				return;
			}
				Sysopt user = (Sysopt) getSession().getAttribute("user");
				TAgent tAgent = tAgentService.get(Long.parseLong(user.getAgtCode()));
				Map map = tlocksService.changeTlockAgt(id, tAgent.getAgtCode());// 执行发货操作
				if((Integer)map.get("code")==1){
					result = tlocksService.installTlocksMethod(lock.getSid().toString(), type, building, unit, name,user.getCommunityId(),user.getAgtCode(),user);//todo Updated by Saber on 2017/7/27 上午11:02
                }else{
					log.info("changeTlockAgt fail");
					result.put("code", 0);
					result.put("msg", "安装硬件失败");
				}
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
			result.put("msg", e.getMessage());
		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", "安装硬件失败");
			log.error(this, e);
		}
		responseBody(result);
	}

    /**
     * app上安装设备调用此接口
     */
	public void installTlocksByApi() {

		String sysoptSid = getRequest().getParameter("sysoptSid");
		String appUserid = getRequest().getParameter("appUserid");
		String appUserToken = getRequest().getParameter("appUserToken");

		String id = getRequest().getParameter("pid");
		String checkcode = getRequest().getParameter("checkcode");
		String type = getRequest().getParameter("type");
		String building = getRequest().getParameter("cBuildingId");
		String unit = getRequest().getParameter("unitId");
		String name = getRequest().getParameter("lockname");
		try {
			Long msg = tlocksService.validateLock(id, checkcode);
			if ( null == msg) {
				result.put("code", 0);
				result.put("msg", "没有匹配的硬件");
			} else {
				Sysopt user = (Sysopt) getSession().getAttribute("user");
				TAgent tAgent = tAgentService.get(Long.parseLong(user.getAgtCode()));
				Map map = tlocksService.changeTlockAgt(id, tAgent.getAgtCode());// 执行发货操作
				if((Integer)map.get("code")==1){
					result = tlocksService.installTlocksMethod(msg.toString(), type, building, unit, name,user.getCommunityId(),user.getAgtCode(),user);//todo Updated by Saber on 2017/7/27 上午11:02
                    //为安装人员生成一把测试钥匙,生成失败也不影响安装结果
					try{
						genKey4Installer();
					}catch(Exception e){
						log.error(this, e);
					}
				}else{
					log.info("changeTlockAgt fail");
					result.put("code", 0);
					result.put("msg", "安装硬件失败");
				}
			}
		} catch (MdKnownRunTimeException e) {
			result.put("code", 0);
			result.put("msg", e.getMessage());
			log.error(this, e);
		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", "安装硬件失败");
			log.error(this, e);
		}
		responseBody(result);
	}

	/**
	 * 为安装人员，生成测试钥匙
	 */
	public void genKey4Installer(){
		String pid = getRequest().getParameter("pid");
		try{
			Sysopt user = (Sysopt) getSession().getAttribute("user");
			TLock lock = tlocksService.getByPid(pid);
			List list = new ArrayList();
			list.add(lock);
			TUsers tuser = tUsersService.getByUserid(user.getAppUserid());
			Date valid = DateUtils.addDay(new Date(), 1);//r
			result = tKeysService.syncTo(tuser, list, DateUtils.formatDatetime(valid, "yyyy-MM-dd"), user.getAgtCode(),DateUtils.addHour(new Date(), 2),null);
		}catch(Exception e){
			log.error(this, e);
			result.put("code", 0);
			result.put("msg", "生成失败");
		}
		responseBody(result);
	}

    /**
     * 已安装记录页面
     */
    public String installLogView() {
        return SUCCESS;
    }

    /**
     * 已安装记录列表
     */
    public void installLogList() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String operationContent = getRequest().getParameter("operationContent");
    	String operator = getRequest().getParameter("operator");
    	String sendTime = getRequest().getParameter("sendTime");

    	if (!StringUtils.isBlank(operationContent)) {
    		where.append(" and t.comm like '%");
    		where.append(operationContent);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(operator)) {
    		where.append(" and t.cUserName = '");
    		where.append(operator);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(sendTime)) {
    		where.append(" and  TO_CHAR (t.cTime,'YYYY-MM-DD') ='");
    		where.append(sendTime);
    		where.append("'");
    	}
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 21) {
    		where.append(" and a.sysoptId =");
			where.append(user.getSid());
		}else if (userRole == 3 || userRole == 4) {
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<LocksInstallLog> locksInstallLog = tlocksService.installList(jqGridPager);
        jqGridQueryMap(TLock.class, getRequest(), locksInstallLog, getResponse(), jqGridPager);
    }

    /**
     * 门禁列表
     */
    public void tlockList() throws Exception{
    	String type = getRequest().getParameter("type");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String communityId = getRequest().getParameter("communityId");
   	 	if (StringUtils.isBlank(communityId)) {
   	 		communityId = user.getCommunityId();
		}
    	List<Map<String, String>> list = tlocksService.tlockList(type,communityId);
    	 responseBody(list);
    }

    /**
     * @Description:接受开发平台硬件分配
     * @return
     * @throws IOException
     */
    public void acceptTlock() throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String lock_data = request.getParameter("lock_data");
			JSONArray jsonArr = JSONArray.fromObject(lock_data);
			if (jsonArr.size()<1) {
				map.put("code", "-1");
				map.put("msg", "数据为空");
				responseBody(map);
				return;
			}
			TLock tlock = null;
			for (int i = 0; i < jsonArr.size(); i++) {
				String pid = jsonArr.getJSONObject(i).getString("pid");
				String checkCode = jsonArr.getJSONObject(i).getString("lock_secret");
				String mac20 = null;
				String ssid1 = null;
				if(jsonArr.getJSONObject(i).has("mac20")){
					mac20 = jsonArr.getJSONObject(i).getString("mac20");
				}
				if(jsonArr.getJSONObject(i).has("ssid1")){
					ssid1 = jsonArr.getJSONObject(i).getString("ssid1");
				}
				StringBuffer where =new StringBuffer();
				where.append(" pid='");
	   			where.append(pid);
	   			where.append("'");
	   			TLock tLockHave = tlocksService.getHql(where.toString());
	   			if (tLockHave == null) {
					tlock = new TLock();
					tlock.setPid(pid);
					tlock.setStatus("-1");
					tlock.setCheckCode(checkCode);
					tlock.setCheckStatus("0");
					tlock.setType("0");
					tlock.setMac20(mac20);
					tlock.setSsid1(ssid1);
					tlocksService.add(tlock);
				}else{
					continue;
				}
			}
			map.put("code", "0");
			map.put("msg", "操作成功");
		} catch (Exception e) {
			log.error(this, e);
			map.put("code", "-1");
			map.put("msg", "操作失败");
		}finally {
			responseBody(map);
		}
	}
    /**
     * @Description:模拟平台发送数据到这里
     * @return
     * @throws IOException
     */
    public String acceptTlock1() throws IOException {
    	List<Map> list = new ArrayList<Map>();
    	for (int i = 1; i <= 3; i++) {
    		String pid = "BLZX00010"+i;
    		Map device = new HashMap();
    		device.put("pid", pid);
    		device.put("privatekey", "privatekey");
    		device.put("mac20", "mac20");
    		device.put("ssid1", "ssid1");
    		device.put("sn", "sn");
    		device.put("lock_secret", "lock_secret");
    		list.add(device);
    	}
    	if (list.size() > 0) {
    		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    		String str = JSONArray.fromObject(list).toString();
    		formparams.add(new BasicNameValuePair("lock_data", str));
    		UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
    		String resp = HttpHelper.doPost("http://localhost:8080/admin/tlocks_acceptTlock.action", uefEntity);
    		log.info("the MIAODOU_NEW_LOCK_URL response=" );
    	}

    	return null;
    }

    /**
     * 回收硬件页面
     */
    public String recoveryListView() {
        return SUCCESS;
    }
    /**
     * 锁厂回收硬件页面
     */
    public String recoveryListView2() {
    	return SUCCESS;
    }

    /**
     * 已安装列表，待回收列表
     */
    public void recoveryList() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	String pid1 = getRequest().getParameter("pid1");
    	String pid2 = getRequest().getParameter("pid2");
    	String type = getRequest().getParameter("type");

        setPage(getRequest(), jqGridPager);
        Sysopt user= (Sysopt)getSession().getAttribute("user"); //todo Created by Saber on 2017/7/27 上午11:44
        int userRole =  (Integer) getSession().getAttribute("userRole");//todo Created by Saber on 2017/7/27 上午11:44
        List<Map<String, Object>> tLocks = tlocksService.recoveryListList(jqGridPager,pid1,pid2,type,user,userRole);//todo Updated by Saber on 2017/7/27 上午11:44
        jqGridQueryMap(TLock.class, getRequest(), tLocks, getResponse(), jqGridPager);
    }

    /**
     * 回收硬件确认页面
     */
    public String recoveryView() {
    	String pids = getRequest().getParameter("pids");
    	getRequest().setAttribute("pids",pids);
        return SUCCESS;
    }
    /**
     * 锁厂回收硬件确认页面
     */
    public String recoveryView2() {
    	String pids = getRequest().getParameter("pids");
    	getRequest().setAttribute("pids",pids);
    	return SUCCESS;
    }

    /**
     * 硬件回收
     */
    public void recovery() throws Exception{
    	try {
    		String pids = getRequest().getParameter("pids");
			Sysopt user= (Sysopt)getSession().getAttribute("user"); //todo Created by Saber on 2017/7/27 上午10:51
			int userRole =  (Integer) getSession().getAttribute("userRole");//todo Created by Saber on 2017/7/27 上午10:51
			result = tlocksService.recoveryMethod(pids,user,userRole);
		} catch (Exception e) {
			result.put("code", 0);
            result.put("msg", "操作失败");
            log.error(this, e);
		}
        responseBody(result);
    }

    /**
     * 硬件检查
     */
    public void check(){
    	String param_ids = getRequest().getParameter("ids");
    	String type = getRequest().getParameter("type");
    	result = tlocksService.checkMethod(param_ids,type);
        responseBody(result);
    }

    /**
     * 锁厂发放测试钥匙页面
     */
    public String testKey() {
    	String sid = getRequest().getParameter("sid");
    	getRequest().setAttribute("sid",sid);
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
        return SUCCESS;
    }


    private TLock tLock = new TLock();

    @Override
    public TLock getModel() {
        return tLock;
    }
}
